package dao_base

import (
	"strings"
	"wrblog-api-go/app/model"
	"wrblog-api-go/app/model/model_base"
	"wrblog-api-go/pkg/errs"
	"wrblog-api-go/pkg/mysql"
	"wrblog-api-go/pkg/utils"
)

func GetArticlePageList(baseArticle model_base.SelectBaseArticle) (baseArticles []model_base.BaseArticleVo, total int64, err error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticlePo{})
	if baseArticle.Title != "" {
		db = db.Where("title like ?", "%"+baseArticle.Title+"%")
	}
	if baseArticle.UserId != 0 {
		db = db.Where("user_id = ?", baseArticle.UserId)
	}
	if baseArticle.LibraryId != 0 {
		db = db.Where("library_id = ?", baseArticle.LibraryId)
	}
	if baseArticle.LabelIds != "" {
		labelIds := strings.Split(baseArticle.LabelIds, ",")
		db = db.Where("label_ids in (?)", labelIds)
	}
	if baseArticle.TypeId != 0 {
		db = db.Where("type_id = ?", baseArticle.TypeId)
	}
	if baseArticle.GroupId != 0 {
		db = db.Where("group_id = ?", baseArticle.GroupId)
	}
	if baseArticle.IsOpen != "" {
		db = db.Where("is_open = ?", baseArticle.IsOpen)
	}
	if baseArticle.Status != "" {
		db = db.Where("status = ?", baseArticle.Status)
	}
	if !baseArticle.StartTime.IsZero() {
		db = db.Where("create_time >= ?", baseArticle.StartTime)
	}
	if !baseArticle.EndTime.IsZero() {
		db = db.Where("create_time <= ?", baseArticle.EndTime)
	}
	db = db.Where("deleted = '0'").Count(&total).Order("create_time desc")
	if baseArticle.PageNum != nil && baseArticle.PageSize != nil {
		db = db.Limit(*baseArticle.PageSize).Offset((*baseArticle.PageNum - 1) * *baseArticle.PageSize)
	} else {
		db = db.Limit(10)
	}
	err = db.Find(&baseArticles).Error
	err = errs.ErrNotFound(err)
	return
}

func GetArticleById(articleId int) (baseArticle model_base.BaseArticleVo, err error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticlePo{})
	err = db.Where("article_id = ? and deleted = '0'", articleId).First(&baseArticle).Error
	err = errs.ErrNotFound(err)
	return
}

func AddArticle(baseArticle model_base.BaseArticlePo) (int, error) {
	db := mysql.Db("salve-1")
	res := db.Create(&baseArticle)
	return baseArticle.ArticleId, errs.ErrNotFound(res.Error)
}

func EditArticle(baseArticle model_base.BaseArticlePo) (int64, error) {
	db := mysql.Db("salve-1")
	res := db.Updates(&baseArticle)
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func RemoveArticle(articleIds []string, uk string) (int64, error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticlePo{})
	db.Where("article_id in (?)", articleIds)
	res := db.Updates(&model_base.BaseArticlePo{BaseEntity: model.BaseEntity{UpdateTime: utils.Time{}, UpdateBy: uk, Deleted: "1"}})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}

func DeleteArticle(articleIds []string) (int64, error) {
	db := mysql.Db("salve-1").Model(&model_base.BaseArticlePo{})
	db.Where("article_id in (?)", articleIds)
	res := db.Delete(&model_base.BaseArticlePo{})
	return res.RowsAffected, errs.ErrNotFound(res.Error)
}
